package com.xinsoft.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinsoft.common.exception.BDException;
import com.xinsoft.entity.dto.CusGateWayParam;
import com.xinsoft.entity.dto.ExcelErrRowDTO;
import com.xinsoft.entity.po.*;
import com.xinsoft.mapper.CusGatewayMapper;
import com.xinsoft.service.CusGatewayService;
import com.xinsoft.service.SysFileHisService;
import com.xinsoft.utils.ExcelUtils;
import com.xinsoft.validator.ValidatorUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* @author lijie
* @description 针对表【cus_gateway(网关)】的数据库操作Service实现
* @createDate 2023-07-03 18:46:26
*/
@Service
public class CusGatewayServiceImpl extends ServiceImpl<CusGatewayMapper, CusGateway>
    implements CusGatewayService{
    @Resource
    public SysFileHisService sysFileHisService;

    @Resource
    CusGatewayMapper cusGatewayMapper;
    @Override
    public Object findPageListByParam(CusGateWayParam param) {
        //分页
        Page<CusGateway> page = new Page<CusGateway>(param.getCurrentPage(), param.getPageSize());
        LambdaQueryWrapper<CusGateway> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件
        queryWrapper
                .like(StrUtil.isNotBlank(param.getKey()),CusGateway::getGatewayName,param.getKey())
                .or().like(StrUtil.isNotBlank(param.getKey()),CusGateway::getGatewayNo,param.getKey());

        IPage<CusGateway> resultPage = cusGatewayMapper.selectPage(page, queryWrapper);
        //返回值
        return resultPage;
    }

    @Override
    public List<CusGateway> findListByParam(CusGateWayParam param) {
        return this.baseMapper.findListByParam(param);    }

    @Override
    public Object importExcel(MultipartFile multipartFile) {
        // 初始化错误行信息list，用来记录导入失败的rowNum
        List<ExcelErrRowDTO> errRowDOs = new ArrayList<>();
        // 对excel是否为空进行check
        if (multipartFile.isEmpty()) {
            throw new BDException("导入失败，请选择文件！");
        }
        //设置excel参数
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<CusGateway> cusGatewayList;
        List<CusGateway> cusGateways = CollectionUtil.newArrayList();

        // 解析excel中的行，cusDeviceList
        try {
            // 解析excel
            cusGatewayList = ExcelImportUtil.importExcel(multipartFile.getInputStream(), CusGateway.class, params);
        } catch (Exception e) {
            throw new BDException("导入失败，文件内容解析错误！");
        }
        JSONObject result = new JSONObject();

        //校验
        if (cusGatewayList.size() > 0) {
            int index = 1;
            for (CusGateway cusGateway : cusGatewayList) {
                index ++;
                // check
                StringBuilder stringBuilder = new StringBuilder();
                ExcelErrRowDTO excelErrRowDO= new ExcelErrRowDTO();
                // 参数校验
                stringBuilder.append(ValidatorUtils.validateExcel(cusGateway));
                // 将错误行信息保存到list
                String errMsg = stringBuilder.toString();
                if(StringUtils.isNotEmpty(errMsg)){
                    excelErrRowDO.setRowIndex(index);
                    excelErrRowDO.setErrMessage(errMsg);
                    errRowDOs.add(excelErrRowDO);
                    continue;
                }
                //保存
                CusGateway gateway = new CusGateway();
                BeanUtils.copyProperties(cusGateway,gateway);
                cusGateways.add(gateway);
            }
            //批量保存
            saveBatch(cusGateways);
            String errFileUrl = ExcelUtils.exportErrRows(errRowDOs,multipartFile,sysFileHisService);
            result.put("errFileUrl",errFileUrl);
            return result;
        }
        return result;
    }
}




